<?php
namespace app\api\controller;

use think\Controller;
use think\Session;

/**
 * 通用上传接口
 * Class Upload
 * @package app\api\controller
 */
class Uploads extends Controller
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 前台通用图片上传接口
     * @return \think\response\Json
     */
    public function upload($file)
    {
        $config = [
            'size' => 209715200,
            'ext'  => 'jpg,gif,png,bmp,jpeg'
        ];

        // $file = $this->request->file('file');
        if($file){
            $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
            $save_path   = '/uploads/';
            $info        = $file->validate($config)->move($upload_path);
    
            if ($info) {
                $result = [
                    'error' => 0,
                    'status' => 0,
                    'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
                ];
            } else {
                $result = [
                    'error'   => 1,
                    'message' => $file->getError()
                ];
            }
            return $result;
        }

        // return json(['error'=>1,'message'=>'参数错误']);
    }

    /**
     * 前台通用zip上传接口
     * @return \think\response\Json
     */
    public function uploadzip()
    {
        $config = [
            'size' => 209715200,
            'ext'  => 'zip'
        ];

        $zip = $this->request->file('zip');
        if($zip){
            $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
            $save_path   = '/uploads/';
            $info        = $zip->validate($config)->move($upload_path);
            if ($info) {
                $result = [
                    'error' => 0,
                    'status' => 1,
                    'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
                ];
            } else {
                $result = [
                    'error'   => 1,
                    'message' => $file->getError()
                ];
            }

            return json($result);          
        }

        return json(['error'=>1,'message'=>'参数错误']);
    }
}

